//
//  CJNewFeatureView.swift
//  SwiftDemo
//
//  Created by Chris on 2017/7/20.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit

class CJNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterhomeBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    
    /// 从xib中获取视图
    class func newFeatureView() -> CJNewFeatureView {
        let nib = UINib.init(nibName: "CJNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! CJNewFeatureView
        
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 设置新特性图片
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let imgV = UIImageView(image: UIImage(named:"new_feature_\(i + 1)"))
            imgV.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(imgV)
        }
        // 设置contentSize
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: 0)
    }
    
    /// 点击进入首页
    @IBAction func enterHome() {
        // 移除当前视图
        removeFromSuperview()
    }
}

// MARK: - scrollView 滚动代理方法
extension CJNewFeatureView: UIScrollViewDelegate {
    
    /// 滚动将要结束
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        // 滚动页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 滚动到最后一页时, 移除新特性界面, 进入首页
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        // 设置进入按钮 显隐
        enterhomeBtn.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    /// 滚动时设值按钮, pageControl
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 只要在滚动, 隐藏进入按钮
        enterhomeBtn.isHidden = true
        // 滚动半屏算一个屏幕偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
}
